Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / admin / orders / [id] / publish / route.ts

1import { NextResponse, type NextRequest } from 'next/server';
2import { getCustomerUser } from '@/app/lib/lumen-auth';
3import { commerceDb } from '@/app/lib/commerce-db';
4import { isAdmin } from '@/app/lib/admin';
5import { sendEmail } from '@/app/lib/email';
6import { env } from '@/app/lib/env';
7import { displayOrderId } from '@/app/lib/orders';
8import { previewReadyHtml, studioOrderMessageHtml } from '@/app/lib/order-emails';
9import { activeProofRevision, customerRevisions, orderMessageConfig, ORDER_MESSAGE_LIMIT, PROOF_PUBLISH_STATUSES, STUDIO_MESSAGE_STATUSES } from '@/app/lib/order-messages';
10import { generateMagicLink } from '@/app/lib/magic-link';
11import { PRODUCTS, sizeLabel, type Orientation } from '@/app/lib/pricing';
12import { FRAMES } from '@/app/data/frames';
13
14export const runtime = 'nodejs';
15export const dynamic = 'force-dynamic';
16
17export async function POST(
18 req: NextRequest,
19 ctx: { params: Promise<{ id: string }> },
20) {
21 const { id } = await ctx.params;
22
23 const user = await getCustomerUser();
24 if (!user || !isAdmin(user.email)) {
25 return NextResponse.json({ error: 'forbidden' }, { status: 403 });
26 }
27
28 let body: { generationId?: unknown; note?: unknown; startRevision?: unknown; sendRevision?: unknown; resumeProof?: unknown } | null;
29 try {
30 body = await req.json();
31 } catch {
32 return NextResponse.json({ error: 'invalid json' }, { status: 400 });
33 }
34 if (!body || (body.note !== undefined && typeof body.note !== 'string')
35 || (body.generationId !== undefined && (typeof body.generationId !== 'string' || !body.generationId))) {
36 return NextResponse.json({ error: 'Invalid proof or message.' }, { status: 400 });
37 }
38 const generationId = body.generationId;
39 const note = body.note?.trim() ?? '';
40 const startRevision = body.startRevision === true;
41 const sendRevision = body.sendRevision === true;
42 const resumeProof = body.resumeProof;
43 if (resumeProof !== undefined && (typeof resumeProof !== 'object' || resumeProof === null
44 || !('generationId' in resumeProof) || typeof resumeProof.generationId !== 'string'
45 || !('feedbackAt' in resumeProof) || typeof resumeProof.feedbackAt !== 'string'
46 || generationId || !note || startRevision || sendRevision)) {
47 return NextResponse.json({ error: 'Choose the current proof and enter a reply.' }, { status: 400 });
48 }
49 if (startRevision && (!generationId || note)) {
50 return NextResponse.json({ error: 'Select the current proof to start a revision.' }, { status: 400 });
51 }
52 if (!generationId && !note) return NextResponse.json({ error: 'Enter a message to send.' }, { status: 400 });
53 if (note.length > ORDER_MESSAGE_LIMIT) {
54 return NextResponse.json({ error: `Messages must be ${ORDER_MESSAGE_LIMIT} characters or fewer.` }, { status: 400 });
55 }
56
57 const admin = commerceDb();
58
59 const { data: orderState, error: readError } = await admin
60 .from('orders')
61 .select('status, config, revision_note, updated_at, current_generation_id')
62 .eq('id', id)
63 .single();
64 if (readError && readError.code !== 'PGRST116') {
65 console.error('[proof publish] Could not load order', id, readError.code);
66 return NextResponse.json({ error: 'Could not load the order.' }, { status: 500 });
67 }
68 if (!orderState) {
69 return NextResponse.json({ error: 'order not found' }, { status: 404 });
70 }
71
72 if (startRevision) {
73 if (orderState.status !== 'awaiting_approval' || orderState.current_generation_id !== generationId) {
74 return NextResponse.json({ error: 'The active proof changed. Reload the order and try again.' }, { status: 409 });
75 }
76 const { data: reopened, error } = await admin.from('orders')
77 .update({ status: 'revision_requested' })
78 .eq('id', id)
79 .eq('status', 'awaiting_approval')
80 .eq('current_generation_id', generationId)
81 .eq('updated_at', orderState.updated_at)
82 .select('id').maybeSingle();
83 if (error) {
84 console.error('[proof publish] Could not start revision', id, error.code);
85 return NextResponse.json({ error: 'Could not start the revision.' }, { status: 500 });
86 }
87 if (!reopened) return NextResponse.json({ error: 'The order changed. Reload the order and try again.' }, { status: 409 });
88 return NextResponse.json({ ok: true });
89 }
90 if (!(generationId ? PROOF_PUBLISH_STATUSES : STUDIO_MESSAGE_STATUSES).includes(orderState.status)) {
91 return NextResponse.json({
92 error: generationId ? 'The order is no longer open for a new proof.' : 'This order is closed to messages.',
93 }, { status: 409 });
94 }
95
96 if (generationId) {
97 if (generationId === orderState.current_generation_id) {
98 return NextResponse.json({ error: 'Select a new render to send as the replacement proof.' }, { status: 409 });
99 }
100 const { data: gen } = await admin
101 .from('generations')
102 .select('id')
103 .eq('id', generationId)
104 .eq('order_id', id)
105 .maybeSingle();
106 if (!gen) return NextResponse.json({ error: 'generation not found for this order' }, { status: 404 });
107 }
108 const revision = activeProofRevision(orderState);
109 if (resumeProof && (!revision || revision.baseGenerationId !== resumeProof.generationId || revision.feedback.at !== resumeProof.feedbackAt)) {
110 return NextResponse.json({ error: 'The proof or feedback changed. Review the latest order and try again.' }, { status: 409 });
111 }
112 if (sendRevision && (!generationId || (revision?.draftId !== generationId && revision?.printUpscale?.generationId !== generationId))) {
113 return NextResponse.json({ error: 'The revision changed. Open the current draft and try again.' }, { status: 409 });
114 }
115
116 const history = orderMessageConfig(orderState.config);
117 const isRevisedProof = !!generationId && !!orderState.current_generation_id;
118 const at = new Date().toISOString();
119 const config = {
120 ...history,
121 ...(generationId ? { proofPublishedAt: at, proofIsRevision: isRevisedProof, revisionDraft: null } : {}),
122 ...(resumeProof ? { proofReviewResumedAt: at, revisionDraft: null } : {}),
123 ...(generationId && revision ? {
124 sentRevisions: [...history.sentRevisions, {
125 generationId, baseGenerationId: revision.baseGenerationId, feedbackAt: revision.feedback.at,
126 feedback: { note: revision.feedback.note, at: revision.feedback.at, generationId: revision.baseGenerationId },
127 ...(revision.printUpscale?.generationId === generationId ? { printUpscale: revision.printUpscale } : {}),
128 }],
129 } : {}),
130 revisions: customerRevisions(orderState.config, orderState.revision_note, orderState.updated_at),
131 studioMessages: note
132 ? [...history.studioMessages, { id: crypto.randomUUID(), note, at, ...(generationId ? { generationId } : {}) }]
133 : history.studioMessages,
134 };
135 // Save the message and proof pointer together. updated_at protects the
136 // conversation from concurrent writes that leave the order status unchanged.
137 const { data: order, error: updErr } = await admin
138 .from('orders')
139 .update(generationId ? {
140 current_generation_id: generationId,
141 status: 'awaiting_approval',
142 revision_note: null,
143 config,
144 } : resumeProof ? { status: 'awaiting_approval', revision_note: null, config } : { config })
145 .eq('id', id)
146 .eq('status', orderState.status)
147 .eq('updated_at', orderState.updated_at)
148 .select('id, user_email, config')
149 .maybeSingle();
150 if (updErr) {
151 console.error('[proof publish] Could not save order update', id, updErr.code);
152 return NextResponse.json({ error: 'Could not save the order update.' }, { status: 500 });
153 }
154 if (!order) {
155 return NextResponse.json({ error: 'The order changed while you were editing. Review its latest state and try again.' }, { status: 409 });
156 }
157
158 if (generationId) {
159 // Keep the historical flag in sync for older readers. The order's
160 // current_generation_id controls which proof is active.
161 const [prior, current] = await Promise.all([
162 admin.from('generations').update({ published: false }).eq('order_id', id).eq('published', true).neq('id', generationId),
163 admin.from('generations').update({ published: true }).eq('order_id', id).eq('id', generationId),
164 ]);
165 if (prior.error || current.error) console.error('[proof publish] Could not sync generation flags', id);
166 }
167
168 // Resolve a human-readable description of the frame the customer
169 // picked, so the email can name it ("Walnut Box Frame Matted Print,
170 // 12 × 16 in") and set expectations for what they'll see on the
171 // framed approve page.
172 const cfg = (order.config ?? {}) as {
173 productId?: 'matted' | 'canvas' | 'classic' | 'stretched';
174 size?: string;
175 orientation?: Orientation;
176 frame?: string;
177 };
178 const product = cfg.productId ? PRODUCTS[cfg.productId] : null;
179 // Transposed for landscape orders so the email names the real shape
180 // ("10 × 8 in" not "8 × 10 in").
181 const sizeLabelStr = product && cfg.size
182 ? sizeLabel(cfg.productId, cfg.size, cfg.orientation ?? 'portrait')
183 : null;
184 const frameLabel = cfg.frame ? FRAMES[cfg.frame as keyof typeof FRAMES]?.label : null;
185 const frameDescription = product && sizeLabelStr
186 ? `${frameLabel ? `${frameLabel} ` : ''}${product.label}, ${sizeLabelStr}`
187 : null;
188
189 const path = generationId || resumeProof || orderState.status === 'awaiting_approval' && !!orderState.current_generation_id
190 ? `/orders/${order.id}/approve` : `/orders/${order.id}`;
191 try {
192 const link = await generateMagicLink(order.user_email, path) ?? `${env.site.url()}${path}`;
193 const orderRef = displayOrderId(order.id);
194 await sendEmail({
195 to: order.user_email,
196 subject: generationId
197 ? `Your ${isRevisedProof ? 'revised ' : ''}Lumen & Gesso proof is ready — ${orderRef}`
198 : `A note from Lumen & Gesso — ${orderRef}`,
199 html: generationId ? previewReadyHtml(order.id, link, frameDescription, note) : studioOrderMessageHtml(order.id, link, note, path.endsWith('/approve')),
200 text: generationId
201 ? `Your portrait proof is ready.${note ? `\n\nA note from the studio:\n${note}` : ''}\n\nReview it: ${link}`
202 : `A note from the studio:\n${note}\n\nView your order: ${link}`,
203 });
204 return NextResponse.json({ ok: true, emailSent: true });
205 } catch {
206 console.error('[proof publish] Order update saved but email failed', id);
207 return NextResponse.json({ ok: true, emailSent: false });
208 }
209}